package com.sjk.flink.util;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sjk.flink.exeception.BaseException;
import com.sjk.flink.exeception.ErrorCode;
import com.sjk.flink.pojo.JsonChecker;
import com.sjk.flink.schema.*;
import networknt.schema.*;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class JsonSchemaUtil {



    public static String getNowTime(String pattern) {
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        return currentTime.format(formatter);
    }

    public static JsonChecker getPatternIdByKey(Map<String,String> SCHEMA_CONFIGS,String schema, String json) {
        JsonChecker checker = new JsonChecker();
        checker.setSuccess(false);
        checker.setExtract_time(getNowTime("yyyy-MM-dd HH:mm:ss"));
        //读取验证配置
        String checkExpression = SCHEMA_CONFIGS.get(schema);
        //schema 不存在直接报错
        if (StringUtils.isBlank(checkExpression)) {
            throw new BaseException(ErrorCode.CODE_E00001.getCode(),schema + " getPatternIdByKey json schema not find ");
        }
        try {
            ObjectMapper mapper = ObjectMapperUtil.getObjectMapper();
            JsonSchema schemaValiator = createSchema(mapper.readTree(checkExpression.toString()));
            JsonNode jsonobj = mapper.readValue(json, JsonNode.class);
            //获取验证结果
            Set<ValidationMessage> validate = schemaValiator.validate(jsonobj);
            //System.out.println(JSON.toJSONString(validate));
            //System.out.println(validate.isEmpty());
            if (!validate.isEmpty()) {
                checker.setSuccess(false);
                checker.setData(json);
                checker.setValidate(validate);
            } else {
                checker.setData(json);
                checker.setSuccess(true);
            }
            return checker;
        } catch (Exception e) {
            System.out.println("验证系统错误：       "+e.getMessage());
            //验证错误，直接抛出
            throw new BaseException(ErrorCode.CODE_E00002.getCode(),e.getMessage());
        }
    }

    public static JsonChecker getPatternIdByIDS(String schema, String json) {
        JsonChecker checker = new JsonChecker();
        checker.setSuccess(false);
        checker.setExtract_time(getNowTime("yyyy-MM-dd HH:mm:ss"));
        StringBuffer checkExpression = new StringBuffer();
        //读取验证配置
        try {
            InputStream inputStream = JsonSchemaUtil.class.getResourceAsStream("/schema/"+schema+".json");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                checkExpression.append(line);
            }
            bufferedReader.close();
            inputStream.close();
        }catch (Exception e) {
            System.out.println("找不到schema文件：       " + e.getMessage());
            e.printStackTrace();
        }

        //schema 不存在直接报错
        if (checkExpression.toString().isEmpty()) {
            throw new BaseException(ErrorCode.CODE_E00001.getCode(),schema+" 的定义文件不存在");
        }
        try {
            ObjectMapper mapper =  ObjectMapperUtil.getObjectMapper();
            JsonSchema schemaValiator = createSchema(mapper.readTree(checkExpression.toString()));
            JsonNode jsonobj = mapper.readValue(json, JsonNode.class);
            //获取验证结果
            Set<ValidationMessage> validate = schemaValiator.validate(jsonobj);
            //System.out.println(validate.isEmpty());
            if (!validate.isEmpty()) {
                checker.setSuccess(false);
                checker.setData(json);
                checker.setValidate(validate);
            } else {
                checker.setData(json);
                checker.setSuccess(true);
            }
            return checker;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("验证系统错误：       "+e.getMessage());
            //验证错误，直接抛出
            throw new BaseException(ErrorCode.CODE_E00002.getCode(),e.getMessage());
        }
    }


    private static JsonSchema createSchema(JsonNode jsonNode) {
        ResourceBundle myBundle = ResourceBundle.getBundle("my-messages",Locale.CHINA);
        /**
        try {
            System.out.println(">>>>>>>>>>>>>>>>>>>>" + new String(myBundle.getString("required").getBytes("ISO-8859-1"), "UTF-8"));
        }catch (Exception ex){
            ex.printStackTrace();
        }
         **/
        SchemaValidatorsConfig config = new SchemaValidatorsConfig();
        config.setResourceBundle(myBundle);
        config.setLocale(Locale.CHINA);

        JsonMetaSchema overrideDateTimeValidator = new JsonMetaSchema
                .Builder(JsonMetaSchema.getV7().getUri())
                .idKeyword("$id")
                .addKeywords(ValidatorTypeCode.getNonFormatKeywords(SpecVersion.VersionFlag.V7))
                .addKeyword(new GroovyKeyword())
                .addKeyword(new TimelinessKeyword())
                .addKeyword(new RelevanceKeyWord())
                .addKeyword(new NotNullKeyword())
                .addFormat(new CustomDateTimeFormat())
                .build();

        return new JsonSchemaFactory
                .Builder()
                .objectMapper(ObjectMapperUtil.getObjectMapper())
                .defaultMetaSchemaURI(overrideDateTimeValidator.getUri())
                .addMetaSchema(overrideDateTimeValidator)
                .build()
                .getSchema(jsonNode,config);
    }

}
